﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Collections.Generic;
using System.Globalization;

namespace MoveItemBetweenFolders.Layouts.MoveItemBetweenFolders
{
    public partial class MoveItem : LayoutsPageBase
    {
        protected SPList list;
        protected string itemUrl;
        protected string[] items;
        protected string listID;
        protected string notificationOK;
        protected string notificationInvalid;
        protected string notification;
        protected bool SUCCESS;
        protected uint lcid;

        protected void Page_Load(object sender, EventArgs e)
        {
            lcid = (uint)CultureInfo.CurrentUICulture.LCID;
            this.ModalTitle.Text = SPUtility.GetLocalizedString("$Resources:PageTitle", "MoveItemBetweenFolders", lcid);
            this.PageTitleinTitleArea.Text = SPUtility.GetLocalizedString("$Resources:PageTitleinTitle", "MoveItemBetweenFolders", lcid);
            btnMove.Text = SPUtility.GetLocalizedString("$Resources:ButtonMoveText", "MoveItemBetweenFolders", lcid);
            this.Description.Text = SPUtility.GetLocalizedString("$Resources:DropDownDesc", "MoveItemBetweenFolders", lcid);
            notificationOK = SPUtility.GetLocalizedString("$Resources:NotificationOK", "MoveItemBetweenFolders", lcid);
            notificationInvalid = SPUtility.GetLocalizedString("$Resources:NotificationInvalid", "MoveItemBetweenFolders", lcid);

            items = Request["items"] != null ? Request["items"].Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries) : new string[] { };
            listID = Request["listID"] != null ? Request["listID"] as string : string.Empty;
            if (!Page.IsPostBack)
            {
                fillFolderList();
                this.lblOutput.Text = string.Empty;
            }
            
            btnMove.Command += new System.Web.UI.WebControls.CommandEventHandler(btnMove_Command);
            
        }

        public void btnMove_Command(object sender, EventArgs e)
        {
            SUCCESS = true;
            using (SPSite site = new SPSite(SPContext.Current.Site.ID))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    SPList list = web.Lists[new Guid(listID)];
                    
                    foreach (string selectedtItem in this.items)
                    {
                        
                        SPListItem item;
                        try
                        {
                            item = list.Items.GetItemById(Convert.ToInt16(selectedtItem));  
                        
                            SPFolder selectedFolder = null;
                            string[] selectedFolderName = ddlFolders.SelectedValue.Split('/');
                            if (selectedFolderName[selectedFolderName.Length - 1] == list.RootFolder.Name)
                                selectedFolder = list.RootFolder;
                            else
                            {
                                string folderUrl = string.Empty;
                                foreach (SPListItem folder in list.Folders)
                                {
                                    folderUrl = folder.Folder.Url;
                                    if (folder.Name == selectedFolderName[selectedFolderName.Length - 1] && folderUrl.Contains(ddlFolders.SelectedValue))
                                    {
                                        selectedFolder = folder.Folder;
                                        break;
                                    }
                                }
                            }
                            List<string> itemUrlParts = new List<string>(item.Url.Split('/'));
                            string itemNumber = itemUrlParts[itemUrlParts.Count - 1];

                            string newUrl = selectedFolder.Url + "/" + itemNumber;
                            SPFile file = web.GetFile(item.Url);


                            file.MoveTo(newUrl);
                            file.Update();
                        }
                        catch //(Exception userChooseFolder)
                        {
                            this.lblOutput.Text = SPUtility.GetLocalizedString("$Resources:ErrorMessage1", "MoveItemBetweenFolders", lcid);
                            SUCCESS = false;
                            break;
                        }
                        
                    }
                    this.lblOutput.Text = SPUtility.GetLocalizedString("$Resources:SuccessMessage1", "MoveItemBetweenFolders", lcid);
                    web.AllowUnsafeUpdates = false;
                    if (SUCCESS)
                        notification = notificationOK;
                    else
                        notification = notificationInvalid;
                   
                    //this.Page.Response.Clear();
                    //this.Page.Response.Write("<script type=\"text/javascript\">window.frameElement.commonModalDialogClose(1, 1);</script>"); 
                    //this.Page.Response.End();
                    Context.Response.Write("<script type=\"text/javascript\">window.frameElement.commonModalDialogClose('"+notification+"',1);</script>");
                    Context.Response.Flush();
                    Context.Response.End();
                }
            }
        }

        protected void fillFolderList()
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.ID))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists.GetList(new Guid(listID), true);
                        //web.GetList(SPUrlUtility.CombineUrl(web.ServerRelativeUrl, "Lists/Tasks"));
                    //this.ddlFolders.Items.Add("Please select a folder...");
                    this.ddlFolders.Items.Add(list.RootFolder.Name);
                    //addFolders(list.RootFolder.SubFolders);
                    foreach (SPListItem folder in list.Folders)
                    {
                        if(folder.Folder.ParentFolder.Name == list.RootFolder.Name)
                            this.ddlFolders.Items.Add(folder.Name);
                        addFolders(folder.Folder.SubFolders);
                        //this.ddlFolders.Items.Add(folder.Name);
                    }
                }
            }
        }

        protected void addFolders(SPFolderCollection folders)
        {
            foreach(SPFolder folder in folders)
            {
                List<string> folderParts = new List<string>(folder.Url.Split('/'));
                string folderName = string.Empty;
                for (int i = 2; i < folderParts.Count; i++)
                {
                    folderName += folderParts[i];
                    if (i != folderParts.Count-1)
                        folderName += "/";
                }
                if(this.ddlFolders.Items.FindByText(folderName) == null)
                    this.ddlFolders.Items.Add(folderName);
                    
                if (folder.SubFolders.Count > 0)
                        addFolders(folder.SubFolders);
                
            }
        }

        
    }
}
